package com.cuitrip.business.tripservice;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.cuitrip.apiservice.TripBusiness;
import com.cuitrip.business.tripservice.model.CategoryInfo;
import com.cuitrip.business.tripservice.model.ServiceInfo;
import com.cuitrip.business.tripservice.ui.IconTextView;
import com.cuitrip.business.user.ChooseCityActivity;
import com.cuitrip.component.item.CtTextView;
import com.cuitrip.service.R;
import com.cuitrip.util.ResourceUtil;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragmentActivity;
import com.lab.component.list.CTRecyclerView;
import com.lab.component.list.simple.CTSimpleRecyclerAdapter;
import com.lab.component.list.simple.CTSimpleViewHolder;
import com.lab.jumper.Jumper;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.ProxyResult;
import com.lab.network.proxy.ApiProxy;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by sheena on 16/4/6.
 */
public class SelectTripCatesActivity extends CustomUiFragmentActivity {


    public static final int MAX_SELECT_NUM = 4;
    @Bind(R.id.ct_recycler_view)
    CTRecyclerView mCtRecyclerView;
    @Bind(R.id.tvNext)
    CtTextView mTvNext;

    private CTSimpleRecyclerAdapter mAdapter;
    private List<CategoryInfo> categoryInfoList = new ArrayList<>();

    public static void startActivity(Context context) {
        Intent intent = new Intent(context, SelectTripCatesActivity.class);
        Jumper.launchActivity(context, intent);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, R.layout.activity_choose_category);
    }

    @Override
    public boolean initCloseTopBar() {
        return false;
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        CustomUiConfig config=new CustomUiConfig();
        config.mLeftStyle= CustomUiConfig.AreaStyle.ICON_STYLE;
        config.mTopbarLeftAreaName=getString(R.string.back_icon);
        config.mTopbarMiddleAreaName = getString(R.string.TRIP_ATTRIBUTE_CATEGORIES_DESC_1);
        return config;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        mCtRecyclerView.setLayoutManager(mLayoutManager);

        mAdapter = new CTSimpleRecyclerAdapter<CategoryInfo>(this, categoryInfoList) {
            @Override
            public int getItemLayoutId(int viewType) {
                return R.layout.item_listview_cates;
            }

            @Override
            public void onNewViewHolder(CTSimpleViewHolder viewHolder, ViewGroup parent, int viewType) {
            }

            @Override
            public void bindData(CTSimpleViewHolder holder, final int position, final CategoryInfo item) {

                TextView tvCates = holder.getView(R.id.tvCates);
                tvCates.setText(item.getName());

                IconTextView icon = holder.getView(R.id.icon);
                if (item.isSelected()) {
                    icon.setText(R.string.correct_icon);
                    icon.setTextColor(ResourceUtil.getColor(R.color.apple_7ecc1e));
                } else {
                    icon.setText(R.string.unselected_icon);
                    icon.setTextColor(ResourceUtil.getColor(R.color.qiaomai_7c706e));
                }
                holder.getView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (item.isSelected()) {
                            item.setSelected(false);
                        } else {
                            if (isValidSelect()) {
                                item.setSelected(true);
                            } else {
                                //TODO 添加提醒
                                /*Snackbar snackbar = Snackbar.make(mTvNext, "ffffff", Snackbar.LENGTH_SHORT);
                                Snackbar.SnackbarLayout layoutView = (Snackbar.SnackbarLayout) snackbar.getView();
                                TextView tv = (TextView) layoutView.findViewById(R.id.snackbar_text);
                                tv.setTextColor(ResourceUtil.getColor(R.color.ct_white));
                                layoutView.setBackgroundColor(ResourceUtil.getThemeColor());
                                snackbar.show();*/
                            }
                        }
                        mAdapter.notifyItemChanged(position);
                    }
                });


            }
        };

        mCtRecyclerView.setAdapter(mAdapter);

    }

    private boolean isValidSelect() {
        int selectNumber = 0;
        for (CategoryInfo categoryInfo : categoryInfoList) {
            if (categoryInfo.isSelected()) {
                selectNumber++;
            }
        }
        if (selectNumber >= MAX_SELECT_NUM) {
            return false;
        } else {
            return true;
        }
    }

    @Override
    public void initData() {
        showLoading();
        Observable.create(
                new Observable.OnSubscribe<List<CategoryInfo>>() {
                    @Override
                    public void call(Subscriber<? super List<CategoryInfo>> subscriber) {
                        ApiProxy apiProxy = new ApiProxy();
                        ProxyResult proxyResult = TripBusiness.getSyncTripCategories(apiProxy, "0");
                        CtApiResponse response = (CtApiResponse) proxyResult.getData();
                        if (response.isResponseNormal()) {
                            List<CategoryInfo> categoryInfoList = (List<CategoryInfo>) response.result;
                            subscriber.onNext(categoryInfoList);
                            subscriber.onCompleted();
                        } else {
                            subscriber.onError(new Throwable(response.msg));
                        }
                    }

                }
        ).subscribeOn(Schedulers.io())
                .map(new Func1<List<CategoryInfo>, List<CategoryInfo>>() {
                    @Override
                    public List<CategoryInfo> call(List<CategoryInfo> categoryInfoList) {
                        List<String> cateTextList = new ArrayList<String>();
                        for (CategoryInfo categoryInfo : categoryInfoList) {
                            cateTextList.add(categoryInfo.getCategory());
                        }
                        String cateText = TextUtils.join(",", cateTextList);
                        ProxyResult proxyResult = TripBusiness.getSyncTripCategories(new ApiProxy(), cateText);
                        CtApiResponse response = (CtApiResponse) proxyResult.getData();
                        if (response.isResponseNormal()) {
                            List<CategoryInfo> fullCateInfoList = (List<CategoryInfo>) response.result;
                            return fullCateInfoList;
                        }
                        return null;
                    }
                }).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<CategoryInfo>>() {
                               @Override
                               public void onCompleted() {

                               }

                               @Override
                               public void onError(Throwable e) {

                               }

                               @Override
                               public void onNext(List<CategoryInfo> list) {
                                   hideLoading();
                                   if (list != null) {
                                       mAdapter.setDataList(list);
                                   }
                               }
                           }

                );
    }


    @OnClick(R.id.tvNext)
    public void clickNext() {

        ChooseCityActivity.chooseLocation(SelectTripCatesActivity.this, ChooseCityActivity.SERVICE_MODE, true);
    }

    private List<CategoryInfo> getSelectedCategoryList() {
        List<CategoryInfo> selectedCategoryList = new ArrayList<>();
        for (CategoryInfo categoryInfo : categoryInfoList) {
            if (categoryInfo.isSelected()) {
                selectedCategoryList.add(categoryInfo);
            }
        }
        return selectedCategoryList;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK && requestCode == ChooseCityActivity.REQUEST_CHOOSE_LOCATION) {

            ServiceInfo serviceInfo = new ServiceInfo();
            serviceInfo.setCateList(getSelectedCategoryList());
            String countryName = data.getStringExtra(ChooseCityActivity.COUNTRY_NAME_KEY);
            String countryAbbr = data.getStringExtra(ChooseCityActivity.COUNTRY_ABBR_KEY);
            String cityAbbr = data.getStringExtra(ChooseCityActivity.CITY_ABBR_KEY);
            String city = data.getStringExtra(ChooseCityActivity.CITY_NAME_KEY);
            String address = data.getStringExtra(ChooseCityActivity.ADDRESS_KEY);
            serviceInfo.setAddress(address);
            serviceInfo.setCountry(countryAbbr);
            serviceInfo.setCity(city);
            serviceInfo.setCityAbbr(cityAbbr);
            TripEditActivity.navigate2TripEditActivity(this, serviceInfo, true);
            finish();
        }
    }

    @Override
    public void onTopbarLeftPress() {
        onBackPressed();
    }
}
